package util

import (
	"crypto/aes"
	"crypto/cipher"
)

// AES CBC 加密
//
// @param key []byte aes密钥,长度 16, 24, or 32 对应  AES-128, AES-192, or AES-256
//
// @param iv  []byte CBC 初始化向量,长度 16
//
// @param plainText []byte 待加密内容
func AESCBCEncrypt(key, iv, plainText []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()

	origData, err := PKCS7Padding(plainText, blockSize)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCEncrypter(block, iv)
	ciphertext := make([]byte, len(origData))
	blockMode.CryptBlocks(ciphertext, origData)
	return ciphertext, nil
}

// AES CBC 解密
//
// @param key []byte aes密钥,长度 16, 24, or 32 对应  AES-128, AES-192, or AES-256
//
// @param iv  []byte CBC 初始化向量,长度 16
//
// @param cipherText []byte 待解密内容
func AESCBCDecrypt(key, iv, cipherText []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)

	origData := make([]byte, len(cipherText))
	blockMode.CryptBlocks(origData, cipherText)
	origData, err = PKCS7UnPadding(origData)
	if err != nil {
		return nil, err
	}
	return origData, nil
}
